﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MMessaging.Address;
using MMessaging.MessagingEx.Common;

namespace MMessaging.Dispatcher
{
	public class DispatcherPlugIn : MServicePlugInBase<MAddressMessageBase>
	{
		private MAddress _serviceAddress;
		public DispatcherPlugIn(MAddress serviceAddress)
		{
			_serviceAddress = serviceAddress;
			RegisterPlugIn(
				_serviceAddress,
				PostMessage);

		}

		protected override void OnMessage(IMTask<MAddressMessageBase> task)
		{
			if (task.CurrentMessage is InternalInvoke)
			{
				var invokeMsg = task.CurrentMessage as InternalInvoke;
				object result = null;
				try
				{
					result = invokeMsg.DelegateFunc();

				}
				catch (Exception)
				{

					throw;
				}
				finally
				{
					this.PostMessageFunc(new InternalInvokeResponse(
						invokeMsg.Sender,
						_serviceAddress,
						DateTime.UtcNow,
						result,
						invokeMsg.MessageID));
				}
			}
		}
	}
}
